#coding=utf-8
from django.shortcuts import render, render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.core.exceptions import ObjectDoesNotExist
from django.template.context import RequestContext
from django import forms
from online.models import User,UserUpload

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import csrf_protect
import os

#首页
def index(req):
    return render_to_response("index.html",{"req": req,}, context_instance=RequestContext(req))
#注册
def regist(req):
    if req.method == 'POST':
       user = User()
       user.username = req.POST.get('username','')
       user.password = req.POST.get('password','')
       user.company = req.POST.get('company','')
       user.email = req.POST.get('email','')
       user.phonenumber = req.POST.get('phonenumber','')
       if user.username != '' and user.password !='':
         #if user.phonenumber == '' or (user.phonenumber.isdigit() and 10000000000<int(user.phonenumber)<1999999999) :
           user.save() #保存进数据库
           resp = HttpResponseRedirect('/online/personal/')
           resp.set_cookie("usernamecookie",user.username)
           return resp
         #else:
          # return HttpResponseRedirect('/online/registwrong/')
    return render_to_response('regist.html', context_instance=RequestContext(req))
#注册失败
def registwrong(req):
    regist(req)
    return render_to_response("registwrong.html",{"req": req,}, context_instance=RequestContext(req))

#登陆
def login(req):
    #if req.session.get('User'):
    #   return HttpResponseRedirect('/online/index/')
    print('=============login',req.method)
    if req.method == 'POST':
       #获取页面中输入的信息
       userName = req.POST['username'] 
       passWord = req.POST['password']
       print(userName,passWord)
       #从数据库里面查找对应用户名的user
       try:
           userlist = User.objects.all()
           usernamelist = []
           for u in userlist:
              usernamelist.append(u.username)
           if userName in usernamelist:
              user = User.objects.get(username = userName) #从数据库里面查找对应用户名的user
              if user.password != passWord:
              #return HttpResponse("用户名或者密码错误～～")
                 response = HttpResponseRedirect('/online/loginwrong/') 
                 return response
              else :
                 print('ok')
                 u = {'username': user.username,
                      'company': user.company,
                      'email': user.email,
                      'phonenumber': user.phonenumber,
                 }
                 req.session['User']= u
                 resp = HttpResponseRedirect('/online/userCenter/')
                 resp.set_cookie("usernamecookie",userName)
                 return resp
           else :
                 response = HttpResponseRedirect('/online/loginwrong/')
                 return response
       except ObjectDoesNotExist:
           return HttpResponseRedirect('') 
    return render_to_response("login.html", context_instance=RequestContext(req))
      
#登陆成功
#def index(req):
#    user = User.objects.get(username = "caoxc")
#    return HttpResponse(user.email)
#登录失败
def loginwrong(req):
    login(req)
    return render_to_response("loginwrong.html",{"req": req,}, context_instance=RequestContext(req))
#关于我们
def aboutus(req):
    return render_to_response("aboutus.html",{"req": req,}, context_instance=RequestContext(req))
#个人主页
def personal(req):
    user = User.objects.get(username = req.COOKIES["usernamecookie"])
    return render(req,'personal.html',{'Email': user.email,'User':user.username,'Company':user.company,'Phone':user.phonenumber,'Passwd':user.password})

#用户中心
def userCenter(req):
    user = User.objects.get(username = req.COOKIES["usernamecookie"])
    return render(req,'userCenter/userCenter_base.html',{'Email': user.email,'User':user.username,'Company':user.company,'Phone':user.phonenumber,'Passwd':user.password})


#文件上传
class UserForm(forms.Form):
    username = forms.CharField()
    headImg = forms.FileField()

def upload(req):
    if req.method == "POST":
        uf = UserForm(req.POST,req.FILES)
        if uf.is_valid():
            headImg = uf.cleaned_data['headImg']
            user = UserUpload()
            user1 = User.objects.get(username = req.COOKIES["usernamecookie"])
            user.username = user1.username
            user.headImg = headImg
            user.save()
            return HttpResponse('上传成功 ！')
    else:
        uf = UserForm
    return render_to_response('upload.html',{'uf':uf})

#数据分类
def example(req):
    return render_to_response("example.html",{"req": req,}, context_instance=RequestContext(req))
#需求详解
def introduce(req):
    return render_to_response("introduce.html",{"req": req,}, context_instance=RequestContext(req))
#运行job
def start(req):
    return render_to_response("introduce.html",{"req": req,}, context_instance=RequestContext(req))
#安装启动集群及服务
def install(req):
    os.system("sudo bash /home/caoxc/docker222/Hadoop/sbin/createMasterSlaveContainer.sh")
    #os.system("echo 'haello word121212'>> dgwdgw/test")
    return render_to_response("install.html",{"req": req,}, context_instance=RequestContext(req))
#数据可视化
def result(req):
    return render_to_response("result.html",{"req": req,}, context_instance=RequestContext(req))
#退出
def logout(req):
    return render_to_response("logout.html",{"req": req,}, context_instance=RequestContext(req))
